package com.android.powerbankpad.module.alipay;

import android.app.Activity;
import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.android.powerbankpad.module.WeakHandler;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class SaveAudioRunnable implements Runnable {

    private String mMoney;
    private Context mContext;

    public SaveAudioRunnable(Activity mContext, String mMoney) {
        this.mMoney = mMoney;
        this.mContext = mContext;
    }

    @Override
    public void run() {
        try {
            File audioFile = new AudioComposeHelper(mContext, NumberToMoneyUtils.toMoneyUnit(mMoney)).getAudioFile();
            if (audioFile == null) {
                return;
            }

            File outDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
            if (!outDir.exists()) {
                outDir.mkdirs();
            }
            File outFile = new File(outDir, mMoney + "元" + ".mp3");

            InputStream mInputStream = new FileInputStream(audioFile);

            BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outFile));
            byte[] arrayOfByte = new byte[2048];
            int length = mInputStream.read(arrayOfByte);
            while (length > 0) {
                outputStream.write(arrayOfByte, 0, length);
                length = mInputStream.read(arrayOfByte);
            }
            outputStream.flush();
            mInputStream.close();
            outputStream.close();
            Message message = new Message();
            message.what = 200;
            weakHandler.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
            Message message = new Message();
            message.what = 400;
            weakHandler.sendMessage(message);
        }
    }

    WeakHandler weakHandler = new WeakHandler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 200) {
                Toast.makeText(mContext, "保存成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(mContext, "保存失败", Toast.LENGTH_SHORT).show();
            }
            return false;
        }
    });

}
